package com.lich.factory;

import com.lich.CommonUtils;
import com.lich.Constants;
import com.lich.Field;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class MysqlFieldFactory implements FieldFactory {

    @Override
    public List<Field> getFieldByTableName(Connection con, String tableName) throws Exception {
        if (CommonUtils.isEmptyString(tableName)) {
            throw new Exception("表名不能为空");
        }
        if (CommonUtils.isEmptyString(Constants.TABLE_SCHEMA)) {
            throw new Exception("表所属数据库名不能为空");
        }
        List<Field> fieldList = new ArrayList<>();
        try {
            //查询表的属性
            Statement stmt = con.createStatement();
            String sql = "select COLUMN_NAME,DATA_TYPE,IS_NULLABLE,COLUMN_COMMENT,COLUMN_KEY from information_schema.`COLUMNS` where table_schema ='" + Constants.TABLE_SCHEMA + "' and table_name = '" + tableName + "'";
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                Field field = new Field();
                field.setName(rs.getString("COLUMN_NAME"));
                field.setType(rs.getString("DATA_TYPE"));
                String isNullable = rs.getString("IS_NULLABLE");
                if ("NO".equals(isNullable)) {
                    field.setNotnull(true);
                } else {
                    field.setNotnull(false);
                }
                field.setComment(rs.getString("COLUMN_COMMENT"));
                String columnKey = rs.getString("COLUMN_KEY");
                if ("PRI".equals(columnKey)) {
                    field.setPrimaryKey(true);
                }
                fieldList.add(field);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            con.close();
        }
        return fieldList;
    }
}
